<?php

declare(strict_types=1);

namespace App\Common\Libary\Third;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Hyperf\Codec\Packer\JsonPacker;
use Hyperf\Contract\PackerInterface;
use Hyperf\Coroutine\Coroutine;
use Hyperf\Guzzle\CoroutineHandler;
use Hyperf\Stringable\Str;
use Mine\Exception\NormalStatusException;

class DaiMengJia
{
    protected Client $client;

    protected PackerInterface $packer;

    protected string $baseUri = 'https://www.dmhw1688.com';

    protected string $appkey='7bjryhg8f34e04621aaa84c5c3d134e046';

    protected string $appSecret = '73e78b4697a499aa268acb469ac6c61';

    protected bool $throwError = false;


    public function __construct()
    {
        $handler = null;
        if (Coroutine::inCoroutine()) {
            $handler = new CoroutineHandler();
        }

        $this->client = new Client([
            'base_uri' => $this->baseUri,
            'timeout' => 3,
            'handler' => $handler,
        ]);
        $this->packer = new JsonPacker();
    }


    public function searchJdItem($keyword ,$p=1,$pageSize = 20)
    {
        $data['keyword'] = htmlspecialchars_decode($keyword);
        $data['pageIndex'] = $p;
        $data['pageSize'] = $pageSize;
        $res = $this->post('/DMJAPPS/apps/third/searchJdGoodsInfo',$data);
        return $res['data']['goodsResps'];
    }

    public function generateParams($uri,$body): array
    {
        $data['appKey'] = $this->appkey;
        $data['requestId'] = md5(Str::uuid()->toString());
        $data['url'] = $uri;
        $data['timestamp'] = time();
        $paramJson = json_encode($body ,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);

        $data['sign'] = $this->SHA256Hex( "{$this->appkey}-{$this->appSecret}-{$uri}-{$data['requestId']}-{$data['timestamp']}-{$paramJson}");
        return $data;
    }

    function SHA256Hex($str){
        $re=hash('sha256', $str, true);
        return bin2hex($re);
    }

    private function post(string $uri,array $params)
    {
        $query = $this->generateParams($uri , $params);

        try {
            $response = $this->client->post($uri."?".urldecode(http_build_query($query)), [
                'json'      =>  $params,
                'timeout'   =>  3,
            ]);
            return $this->packer->unpack((string) $response->getBody());
        } catch (GuzzleException $e) {
            if($this->throwError){
                throw new NormalStatusException('请求失败'.$e->getMessage());
            }
            return false;
        }
    }
}